from urllib import parse
from django.http import HttpResponse
from django.shortcuts import render
from analysis import analysis
import json
from user.models import Position, Keyword
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
import pandas as pd
from django.db.models import *
from spider.lagou_spider import LagouSpider


def check_login(request):
    if request.session.get("is_login") is None:
        # 还没有登录
        return False
    return True


# Create your views here.
def search(request):
    """
    搜索职位接口
    :param request:
    :return:
    """
    if not check_login(request):
        # 判断登录状态
        return redirect('/user/login/')
    # 获取参数
    keyword = parse.unquote(request.GET.get('keyword'))
    request.session['keyword'] = keyword
    # 如果不存在关键词，启动爬虫爬取数据
    if len(Keyword.objects.filter(word=keyword)) == 0:
        LagouSpider().spider(keyword)

    return HttpResponse(json.dumps({'success': 1}), content_type="application/json,charset=utf-8")


def get_data(request):
    if not check_login(request):
        # 判断登录状态
        return redirect('/user/login/')
    # keyword = parse.unquote(request.GET.get('keyword'))
    keyword = request.session.get('keyword')
    print(keyword)
    # keyword = 'java'
    data = analysis.get_data(keyword)
    result = dict()
    result['education'] = analysis.education_analysis(data)
    result['salary'] = analysis.salary_analysis(data)
    result['location'] = analysis.location_analysis(data)
    result['experience'] = analysis.experience_analysis(data)
    result['profession'] = analysis.profession_analysis(data)
    result['company'] = analysis.company_analysis(data)
    result['requirement'] = analysis.requirement_analysis(data)
    result['benifits'] = analysis.benifits_analysis(data)
    return HttpResponse(json.dumps(result), content_type="application/json,charset=utf-8")


def show_html(request):
    if not check_login(request):
        # 判断登录状态
        return redirect('/user/login/')
    return render(request, 'show.html')
